//
//  LGCommonScreenView.m
//  HeartDiseaseManage
//
//  Created by 1234 on 2023/9/5.
//  筛选View

#import "LGCommonScreenView.h"

#import "LGMedicineBallScreenHeader.h"
#import "LGMedicineBallScreenFooter.h"
#import "LGMedicineBallScreenCell.h"
#import "LGCollectionViewLeftFlowLayout.h"
@interface LGCommonScreenView()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
/**   */
@property (nonatomic , strong)UIView *baseView;
/**   */
@property (nonatomic , strong)UILabel *titleLabel;
/**   */
@property (nonatomic , strong)UIButton *closeBtn;
/**   */
@property (nonatomic , strong)UIView *bottomView;
/**   */
@property (nonatomic , assign)CGFloat minWidth;
/**   */
@property (nonatomic , strong)NSArray *dataArray;

@end

@implementation LGCommonScreenView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.minWidth = viewPix(100);
        self.backgroundColor = [UIColor colorWithString:@"#000000" alpha:0];
        [self addSubview:self.baseView];
        [self.baseView addSubview:self.collectionView];
        [self.baseView addSubview:self.titleLabel];
        [self.baseView addSubview:self.closeBtn];
        [self.baseView addSubview:self.bottomView];
        [self.bottomView addSubview:self.resetBtn];
        [self.bottomView addSubview:self.sureBtn];
    }
    return self;
}

-(void)setItemArray:(NSArray *)itemArray{
    _itemArray = itemArray;
    NSMutableArray *tempArray = [NSMutableArray array];
    NSMutableDictionary *newScreenDic = [NSMutableDictionary dictionary];
    for (NSInteger i=0; i<itemArray.count; i++) {
        NSDictionary *tempDic = itemArray[i];
        NSArray *items = tempDic[@"items"];
        if(items.count>0 || [LGNSString(tempDic[@"key"]) isEqualToString:@"radio_time"] || [LGNSString(tempDic[@"key"]) isEqualToString:@"multiple_time"]){
            [tempArray addObject:tempDic];
        }
        //老数据
        NSString *key = LGNSString(tempDic[@"key"]);
        
        if([self.screenDic.allKeys containsObject:key]){
            NSArray *keyArray = [self.screenDic[LGNSString(tempDic[@"key"])] allKeys];
            NSMutableDictionary *mutDic = [NSMutableDictionary dictionaryWithDictionary:self.screenDic[LGNSString(tempDic[@"key"])]];
            for (NSInteger j=0; j<items.count; j++) {
                NSDictionary *itemDic = items[j];
                NSString *title = LGNSString(itemDic[@"title"]);
                if([keyArray containsObject:title]){
                    [mutDic setValue:LGNSString(itemDic[@"patient_ids"]) forKey:title];
                }
            }
            [newScreenDic setValue:mutDic forKey:key];
        }
    }
    //刷新默认选中的数据
    self.screenDic = [NSMutableDictionary dictionaryWithDictionary:newScreenDic];
    self.dataArray = tempArray;
    [self.collectionView reloadData];
}


-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return self.dataArray.count;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSArray *itemArray = self.dataArray[section][@"items"];
    return itemArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSString *key = LGNSString(self.dataArray[indexPath.section][@"key"]);
    LGMedicineBallScreenCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    NSString *title = LGNSString(self.dataArray[indexPath.section][@"items"][indexPath.item][@"title"]);
    NSString *count = LGNSString(self.dataArray[indexPath.section][@"items"][indexPath.item][@"count"]);
    NSDictionary *tempDic = [self.screenDic objectForKey:key];
    cell.content = (indexPath.item == 0)?title:[NSString stringWithFormat:@"%@(%@)",title,count];
    cell.isSelect = ([tempDic.allKeys containsObject:title]||(tempDic.allKeys.count == 0 && indexPath.item == 0))?YES:NO;
    if(indexPath.section == 0){
        NSLog(@">>>???>>>%@",tempDic);
    }
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSString *key = LGNSString(self.dataArray[indexPath.section][@"key"]);
    NSString *startKey = [NSString stringWithFormat:@"%@_start",key];
    NSString *endKey = [NSString stringWithFormat:@"%@_end",key];
    NSString *type = LGNSString(self.dataArray[indexPath.section][@"type"]);
    NSString *title = LGNSString(self.dataArray[indexPath.section][@"items"][indexPath.item][@"title"]);
    NSString *ids = LGNSString(self.dataArray[indexPath.section][@"items"][indexPath.item][@"ids"]);
    NSString *allTitle = LGNSString(self.dataArray[indexPath.section][@"items"][0][@"title"]);
    if([type isEqualToString:@"radio"] || [type isEqualToString:@"radio_time"]){
        //单选
        if(indexPath.item == 0){
            //选全部
            [self.screenDic removeObjectForKey:key];
        }else{
            [self.screenDic setValue:@{title:ids} forKey:key];
            if([self.screenDic.allKeys containsObject:startKey]){
                [self.screenDic removeObjectForKey:startKey];
            }
            
            if([self.screenDic.allKeys containsObject:endKey]){
                [self.screenDic removeObjectForKey:endKey];
            }
        }
    }else{
        //多选
        if(indexPath.item == 0){
            //选全部
            [self.screenDic removeObjectForKey:key];
        }else{
            //多选
            NSMutableDictionary *temDic = [NSMutableDictionary dictionaryWithDictionary:self.screenDic[key]];
            LGMedicineBallScreenCell *cell = (LGMedicineBallScreenCell *)[collectionView cellForItemAtIndexPath:indexPath];
            if(cell.isSelect == YES){
                //取消选中
                if(temDic.allKeys.count == 1){
                    //选全部
                    [self.screenDic removeObjectForKey:key];
                }else{
                    //取消选中某个
                    [temDic removeObjectForKey:title];
                }
            }else{
                //选中
                [temDic setValue:ids forKey:title];
                if([temDic.allKeys containsObject:allTitle]){
                    [temDic removeObjectForKey:allTitle];
                }
            }
            [self.screenDic setValue:temDic forKey:key];
            if([self.screenDic.allKeys containsObject:startKey]){
                [self.screenDic removeObjectForKey:startKey];
            }
            
            if([self.screenDic.allKeys containsObject:endKey]){
                [self.screenDic removeObjectForKey:endKey];
            }
        }
    }
    [self.collectionView reloadData];
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    NSString *title = LGNSString(self.dataArray[indexPath.section][@"items"][indexPath.item][@"title"]);
    NSString *count = LGNSString(self.dataArray[indexPath.section][@"items"][indexPath.item][@"count"]);
    NSString *content = (indexPath.item == 0)?title:[NSString stringWithFormat:@"%@(%@)",title,count];
    CGFloat width = [content textWidthWithFont:LGFontWeight(15, UIFontWeightMedium) maxHeight:MAXFLOAT]+viewPix(20);
    width = (width>self.minWidth)?width:self.minWidth;
    return CGSizeMake(width, viewPix(32));
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(Screen_W, viewPix(40));
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    NSString *type = LGNSString(self.dataArray[section][@"type"]);
    CGFloat height = ([type isEqualToString:@"radio_time"]||[type isEqualToString:@"multiple_time"])?viewPix(55):viewPix(15);
    return CGSizeMake(Screen_W, height);
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    NSString *type = LGNSString(self.dataArray[indexPath.section][@"type"]);
    __block NSString *key = LGNSString(self.dataArray[indexPath.section][@"key"]);
    if(kind == UICollectionElementKindSectionHeader){
        LGMedicineBallScreenHeader *headView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
        headView.title = LGNSString(self.dataArray[indexPath.section][@"title"]);
        return headView;
        
    }else if(kind == UICollectionElementKindSectionFooter && ([type isEqualToString:@"radio_time"] || [type isEqualToString:@"multiple_time"])){
        LGMedicineBallScreenFooter *footView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath];
        footView.key = key;
        __block NSString *startKey = [NSString stringWithFormat:@"%@_start",key];
        __block NSString *endKey = [NSString stringWithFormat:@"%@_end",key];
        footView.startTF.text = [self.screenDic.allKeys containsObject:startKey]?LGNSString(self.screenDic[startKey]):@"";
        footView.endTF.text = [self.screenDic.allKeys containsObject:endKey]?LGNSString(self.screenDic[endKey]):@"";
        __weak typeof(self) weakSelf = self;
        footView.screenDateSelectStart = ^(NSString * _Nonnull key, NSString * _Nonnull date) {
            [weakSelf.screenDic setValue:date forKey:startKey];
            [weakSelf.screenDic removeObjectForKey:key];
            [weakSelf.collectionView reloadData];
        };
        
        footView.screenDateSelectEnd = ^(NSString * _Nonnull key, NSString * _Nonnull date) {
            [weakSelf.screenDic setValue:date forKey:endKey];
            [weakSelf.screenDic removeObjectForKey:key];
            [weakSelf.collectionView reloadData];
        };
        return footView;
        
    }else{
        UICollectionReusableView *footView = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"normalFooter" forIndexPath:indexPath];
        footView.backgroundColor = [UIColor whiteColor];
        return footView;
    }
}

//重置
-(void)resetDataAction{
    [self.screenDic removeAllObjects];
    [self.collectionView reloadData];
}

//弹出
-(void)showScreenViewAnimation{
    self.hidden = NO;
    [UIView animateWithDuration:0.4 animations:^{
        self.baseView.frame = CGRectMake(0, viewPix(110), Screen_W, Screen_H);
        self.backgroundColor = [UIColor colorWithString:@"#000000" alpha:0.5];
    }];
}

//关闭
-(void)closeViewAction{
    [UIView animateWithDuration:0.4 animations:^{
        self.baseView.frame = CGRectMake(0, Screen_H, Screen_W, Screen_H);
        self.backgroundColor = [UIColor colorWithString:@"#000000" alpha:0];
    } completion:^(BOOL finished) {
        self.hidden = YES;
    }];
}

#pragma mark
#pragma mark ====> 创建控件
-(NSMutableDictionary *)screenDic{
    if(!_screenDic){
        _screenDic = [NSMutableDictionary dictionary];
    }
    return _screenDic;
}

-(UIView *)baseView{
    if(!_baseView){
        _baseView = [[UIView alloc]initWithFrame:CGRectMake(0, Screen_H, Screen_W, Screen_H)];
        _baseView.backgroundColor = [UIColor whiteColor];
        _baseView.cornerRidus = viewPix(15);
    }
    return _baseView;
}

-(UICollectionView *)collectionView{
    if(!_collectionView){
        LGCollectionViewLeftFlowLayout *layout = [[LGCollectionViewLeftFlowLayout alloc]init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.minimumInteritemSpacing = viewPix(12);
        layout.minimumLineSpacing = viewPix(12);
        _collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, viewPix(50), Screen_W, Screen_H-viewPix(244)) collectionViewLayout:layout];
        [_collectionView registerClass:[LGMedicineBallScreenHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
        [_collectionView registerClass:[LGMedicineBallScreenFooter class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
        [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"normalFooter"];
        [_collectionView registerClass:[LGMedicineBallScreenCell class] forCellWithReuseIdentifier:@"cell"];
        _collectionView.contentInset = UIEdgeInsetsMake(0, viewPix(20), 0, viewPix(18));
        _collectionView.backgroundColor = [UIColor whiteColor];
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
    }
    return _collectionView;
}

-(UILabel *)titleLabel{
    if(!_titleLabel){
        _titleLabel = [UILabel lableWithText:@"全部筛选" colorString:@"#333333" textFont:LGFontWeight(16, UIFontWeightSemibold) textAlignment:NSTextAlignmentCenter lines:1];
        _titleLabel.frame = CGRectMake(viewPix(100), viewPix(20), Screen_W-viewPix(200), viewPix(22));
    }
    return _titleLabel;
}

-(UIButton *)closeBtn{
    if(!_closeBtn){
        _closeBtn = [UIButton buttonWithImage:@"closeGray16" selectImage:@"closeGray16"];
        _closeBtn.frame = CGRectMake(Screen_W-viewPix(46), viewPix(13.5), viewPix(36), viewPix(36));
        [_closeBtn addTarget:self action:@selector(closeViewAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeBtn;
}

-(UIView *)bottomView{
    if(!_bottomView){
        _bottomView = [[UIView alloc]initWithFrame:CGRectMake(-1, kMaxY(self.collectionView.frame), Screen_W+2, viewPix(84)+2)];
        _bottomView.layer.borderColor = [UIColor colorWithString:@"#EAEAEA"].CGColor;
        _bottomView.backgroundColor = [UIColor whiteColor];
        _bottomView.layer.borderWidth = 1;
    }
    return _bottomView;
}

-(UIButton *)resetBtn{
    if(!_resetBtn){
        _resetBtn = [UIButton buttonWithTitle:@"重置" titleFont:LGFontWeight(16, UIFontWeightMedium) normalColor:@"#429BFF" selectColor:@"#429BFF"];
        _resetBtn.frame = CGRectMake(viewPix(47), viewPix(12), (Screen_W-viewPix(118))/2.0, viewPix(46));
        _resetBtn.layer.borderColor = [UIColor colorWithString:@"#429BFF"].CGColor;
        _resetBtn.layer.borderWidth = 1;
        _resetBtn.cornerRidus = 10;
    }
    return _resetBtn;
}

-(UIButton *)sureBtn{
    if(!_sureBtn){
        _sureBtn = [UIButton buttonWithTitle:@"确定" titleFont:LGFontWeight(16, UIFontWeightMedium) normalColor:@"#FFFFFF" selectColor:@"#FFFFFF"];
        _sureBtn.frame = CGRectMake(kMaxX(self.resetBtn.frame)+viewPix(24), viewPix(12), (Screen_W-viewPix(118))/2.0, viewPix(46));
        _sureBtn.backgroundColor = [UIColor colorWithString:@"#429BFF"];
        _sureBtn.cornerRidus = 10;
    }
    return _sureBtn;
}


@end
